package com.example.firstjavamqtt.controller.mqtt_api;

import com.alibaba.fastjson.JSONObject;
import com.example.firstjavamqtt.common.excepiton.GlobalException;
import com.example.firstjavamqtt.common.result.Result;
import com.example.firstjavamqtt.common.result.ResultCodeEnum;
import com.example.firstjavamqtt.model.dto.mqtt.MqttTemperatureHumidityDto;
import com.example.firstjavamqtt.service.log.DeviceLogService;
import com.example.firstjavamqtt.service.log.TemperatureHumidityLogService;
import com.example.firstjavamqtt.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/mqtt/temperatureHumidity")
@Api(tags = "温湿度消息接口")
public class TemperatureHumidityController {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    TemperatureHumidityLogService temperatureHumidityLogService;

    @Autowired
    DeviceLogService deviceLogService;

    @ApiOperation("获取温度和湿度")
    @GetMapping(value = "/getTempAndHumidity/{deviceId}")
    public Result controlLed(HttpServletRequest request,
                             @PathVariable String deviceId) {
        //从redis中取
        MqttTemperatureHumidityDto dto = ((MqttTemperatureHumidityDto) redisUtil.get("TempHumidity:" + deviceId));
        //redis查不到值 那么肯定是设备离线了或者其他问题
        if(dto==null){
            throw new GlobalException(ResultCodeEnum.OFFLINE);
        }
        temperatureHumidityLogService.saveTemperatureHumidityLog(dto,request);
        deviceLogService.saveDeviceLog(JSONObject.toJSONString(dto),request);
        return Result.ok(dto);
    }
}
